const scerect = "mushan"
const jwt = require('jsonwebtoken');
const cookieKey = "token"
//颁发jwt
exports.generateToken = function (res, maxAge = 3600*24, payload = {}) { 
    const token = jwt.sign(payload, scerect, {expiresIn: maxAge});
    //添加到cookie
    // res.cookie(cookieKey, token, {maxAge: maxAge * 1000, path:"/"});
    //添加到header
    res.header("Authorization", token);
};

exports.verifyToken = function (req) { 
    //从cookie中获取token
    let token = req.cookies[cookieKey];
    //从header中获取token
    if(!token) token = req.headers.authorization;
    if(!token) return new Error("未登录");
    //验证token是否携带bearea
    //if(!token.startsWith("Bearer ")) return null;
    token = token.split(" ")
    token = token.lenth > 1 ? token[1] : token[0];

    //验证token
    try {
        return jwt.verify(token, scerect);
    } catch {
        return new Error("token验证失败,请重新登录");
    }
};